/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/no-unused-state */
import React, { Component, CSSProperties } from 'react';
import { Button, Card, Icon } from 'choerodon-ui';
import { connect } from 'dva';
import RGL, { WidthProvider } from 'react-grid-layout';
import { debounce } from 'lodash';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

import styles from './style.less';
import { StateType } from './typing.d';

const ReactGridLayout = WidthProvider(RGL);

const layoutContainerStyle = { position: 'relative', height: '100%', width: '100%' };

const buttonStyle = { float: 'right', marginRight: '12px' };

const setLayoutButtonStyle = { float: 'right', marginRight: '12px' };

interface ProduceDashboardProps {
  dispatch: any;
  medicalMedicines: StateType;
  loading: boolean;
  width: number;
}

const Head = (props: any) => {
  const { setting, loading, startSettingLayout, cancelSettingLayout, saveLayout } = props as any;
  if (loading !== true) {
    if (setting === true) {
      return (
        <div style={{ flex: '1 auto' }}>
          <Button type="primary" style={buttonStyle as CSSProperties} onClick={saveLayout}>
            保存
          </Button>
          <Button style={buttonStyle as CSSProperties} onClick={cancelSettingLayout}>
            取消
          </Button>
        </div>
      );
    } else {
      return (
        <div style={{ flex: '1 auto' }}>
          <Button
            icon="view_quilt"
            style={setLayoutButtonStyle as CSSProperties}
            onClick={startSettingLayout}
          >
            设置布局
          </Button>
        </div>
      );
    }
  }
  return null;
};

class ProduceDashboard extends Component<ProduceDashboardProps> {
  originLayout = null; // 存储进入设计状态之前的 layout

  constructor(props: any) {
    super(props);
    this.state = {
      setting: false, // 布局按钮
      loading: false,
      layout: [], // 现有的布局数据
      cards: [], // 现有的布局 对应的 组件
      ifResize: false, // 如果有其他页面resize了，这时要进行一下本页面重新刷新
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'produceDashboard/fetchLayoutAndInit',
    }).then((res: any) => {
      if (res) {
        this.loadCards(
          res.map((card: { [x: string]: any; sourceCode: any }) => {
            const { sourceCode, ...rest } = card;
            return { ...rest, i: sourceCode, minW: 3, minH: 3 };
          })
        );
      }
    });
    const callback = this.onreSize;
    const resize = debounce(() => {
      callback();
    }, 1000);
    window.addEventListener('resize', resize);
  }

  onResize() {
    const callback = this.onreSize;
    debounce(() => {
      callback();
    }, 1000);
  }

  // 当切换到其他页面并进行了页面缩放之后重新resize当前页面
  resize = debounce(() => {
    window.dispatchEvent(new Event('resize'));
    this.setState({
      loading: false,
      ifResize: false,
    });
  }, 1000);

  // 当手动修改resize之后触发一次页面resize使得bizcharts重新渲染
  handResize = debounce(() => {
    window.dispatchEvent(new Event('resize'));
  }, 100);

  /**
   * 响应式瀑布
   */
  onreSize = () => {};

  /**
   * 将 卡片 加载成 layout
   */
  loadCards(layouts = []) {
    let layout = layouts;
    const cs = layout.map((c: any) => c.i);
    let cards: ({ name: any; component: JSX.Element } | null)[] = [];
    this.importCard(...cs)
      .then(cmps => {
        cards = cs.map((name, i) => {
          const cmp = cmps[i];
          const WorkplaceCard = cmp.default;
          if (cmp && cmp.default) {
            return {
              name,
              component: <WorkplaceCard />,
            };
          }
          return null;
        });
      })
      .catch(error => {
        layout = [{ code: 'error', x: 0, y: 0, w: 4, h: 8 }] as any;
        cards = [
          {
            name: 'error',
            component: <Card title="Error">{`${error}`}</Card>,
          },
        ];
      })
      .finally(() => {
        this.setState({
          loading: false,
          layout,
          cards,
        });
      });
  }

  /**
   * 加载卡片组件
   */
  async importCard(...cards: any[]) {
    try {
      const arrays = cards.map(card => import(`./components/${card}`));
      const components = await Promise.all([...arrays]);
      return components;
    } catch (e) {
      return Promise.reject(e);
    }
  }

  startSettingLayout = () => {
    const { layout } = this.state as any;
    this.setState(
      {
        setting: true,
      },
      () => {
        this.originLayout = layout;
      }
    );
  };

  saveLayout = () => {
    const { layout } = this.state as any;
    // const { dispatch } = this.props;
    this.setState(
      {
        setting: false,
      },
      () => {
        if (layout) {
          this.originLayout = layout;
          this.loadCards(this.originLayout as any);
        }
      }
    );
  };

  cancelSettingLayout = () => {
    this.loadCards(this.originLayout as any);
    this.setState({
      setting: false,
    });
  };

  onLayoutChange = (layout: any) => {
    if (layout.length === 1 && layout[0].name === 'error') return;
    this.setState({
      layout,
    });
  };

  renderCard = () => {
    const { setting = false, cards = [] } = this.state as any;
    return cards.map((item: any) => {
      if (setting === true) {
        return (
          <div key={item.name} className={styles.card}>
            {item.component}
            <div className={styles.dragCard} />
            <Icon
              type="close"
              className={styles.closeBtn}
              onClick={() => {
                this.handleRemoveCard(item.name);
              }}
              style={{ position: 'absolute', top: 0, right: 0 }}
            />
          </div>
        );
      } else {
        return (
          <div key={item.name} className={styles.card}>
            {item.component}
          </div>
        );
      }
    });
  };

  handleRemoveCard(_name: any) {}

  render() {
    const { setting, layout, loading } = this.state as any;
    // const { loading1 } = this.props as any;
    const allCards = this.renderCard();

    // 定义 header props
    const headProps = {
      loading,
      setting,
      startSettingLayout: this.startSettingLayout,
      cancelSettingLayout: this.cancelSettingLayout,
      saveLayout: this.saveLayout,
    };

    return (
      <PageHeaderWrapper
        title="我的工作台"
        header={<Head {...headProps} />}
        contentProps={{ style: { padding: 0, height: '100%', background: '#F8F8F8' }, className: styles['produce-dashboard'] }}
      >
        <ReactGridLayout
          style={layoutContainerStyle as CSSProperties}
          layout={layout}
          className={styles.gridLayoutContainer}
          isDraggable={setting}
          isResizable={setting}
          cols={12}
          rowHeight={30}
          onLayoutChange={this.onLayoutChange}
          compactType="horizontal"
          onResize={this.handResize}
        >
          {allCards}
        </ReactGridLayout>
      </PageHeaderWrapper>
    );
  }
}

export default connect(
  ({
    produceDashboard,
    loading,
  }: {
    produceDashboard: StateType;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) =>
    ({
      produceDashboard,
      loading1:
        !!loading.effects['produceDashboard/fetchLayoutAndInit'] ||
        !!loading.effects['produceDashboard/saveLayout'],
    } as any)
)(ProduceDashboard);
